package com.sunseen.capacitormachine.modules.query;

import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.databinding.FragmentQuerySurgeCurveBinding;

import java.util.ArrayList;
import java.util.List;

public class QuerySurgeCurveFragment extends BaseFragment {

    private String uid = "";

    void setUniqueId(String uid) {
        this.uid = uid;
    }

    @Override
    protected int setLayout() {
        return R.layout.fragment_query_surge_curve;
    }

    private FragmentQuerySurgeCurveBinding binding;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        binding = (FragmentQuerySurgeCurveBinding) viewDataBinding;
        binding.toolBar.setNavigationOnClickListener((v) -> pop());
        initLineChart1();
        initLineChart2();
        querySurgeData();
    }

    private void querySurgeData() {
        RestClient.builder().url(HttpUtil.SurgeData)
                .params("uid", uid)
                .success((String response) -> {
                    JSONObject jsonObject = JSON.parseObject(response);
                    if (jsonObject.getInteger("status") == 1) {
                        JSONObject dataObj = jsonObject.getJSONObject("data");
                        if (dataObj != null) {
                            JSONObject surgeData1 = dataObj.getJSONObject("surgeData1");
                            if (surgeData1 != null) {
                                drawLineData(1, surgeData1, lineChart1);
                            }
                            JSONObject surgeData2 = dataObj.getJSONObject("surgeData2");
                            if (surgeData2 != null) {
                                drawLineData(2, surgeData2, lineChart2);
                            }
                        } else {
                            Toast.makeText(_mActivity, "查询浪涌数据失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(_mActivity, "查询浪涌数据失败", Toast.LENGTH_SHORT).show();
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "查询浪涌数据失败", Toast.LENGTH_SHORT).show();
                })
                .error((int code, String msg) -> {
                    Toast.makeText(_mActivity, "查询浪涌数据错误", Toast.LENGTH_SHORT).show();
                    Log.e("test", "code = " + code + " msg = " + msg);
                })
                .build()
                .get();
    }

    private void drawLineData(int type, JSONObject jsonObject, LineChart lineChart) {
        if (jsonObject != null) {
            int baseValue = jsonObject.getIntValue("baseValue");
            LineData lineData = lineChart.getLineData();
            ILineDataSet baseLineSet = lineData.getDataSets().get(0);
            baseLineSet.clear();
            baseLineSet.addEntry(new Entry(0, baseValue));
            baseLineSet.addEntry(new Entry(220, baseValue));
            Integer surgeResult = jsonObject.getInteger("timeGap");
            String surgeResultStr = "未知";
            if (surgeResult != null) {
                switch (surgeResult) {
                    case 0:
                        surgeResultStr = "接触不良或空位";
                        break;
                    case 1:
                        surgeResultStr = "未通过";
                        break;
                    case 2:
                        surgeResultStr = "通过";
                }
            }
            if (type == 1) {
                binding.tvSurge1Result.setText(surgeResultStr);
            } else {
                binding.tvSurge2Result.setText(surgeResultStr);
            }

            ILineDataSet set = lineData.getDataSets().get(1);
            List<Integer> voltageList = JSON.parseArray(jsonObject.getString("data"), Integer.class);
            set.clear();
            for (int i = 0, size = voltageList.size(); i < size; i++) {
                set.addEntry(new Entry(i + 1, voltageList.get(i)));
            }
            lineChart.notifyDataSetChanged();
            lineChart.invalidate();
        } else {
            Toast.makeText(_mActivity, "查询浪涌" + type + "数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    private LineChart lineChart1;

    private void initLineChart1() {
        lineChart1 = binding.lineChart1;
        setLineChartParameter(lineChart1);
        initLineData(lineChart1, "浪涌1", 450);
    }

    private LineChart lineChart2;

    private void initLineChart2() {
        lineChart2 = binding.lineChart2;
        setLineChartParameter(lineChart2);
        initLineData(lineChart2, "浪涌2", 450);
    }

    private void initLineData(LineChart lineChart, String labelName, int baseValue) {

        LineDataSet baseLineSet = new LineDataSet(new ArrayList<>(), getString(R.string.surging_upper_limit));
        baseLineSet.addEntry(new Entry(0, baseValue));
        baseLineSet.addEntry(new Entry(220, baseValue));
        baseLineSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        baseLineSet.setMode(LineDataSet.Mode.LINEAR);
        baseLineSet.setLineWidth(2f);
        baseLineSet.setCircleRadius(2f);
        baseLineSet.setFillAlpha(65);
        final int orangeColor = getResources().getColor(R.color.orange);
        baseLineSet.setColor(orangeColor);
        baseLineSet.setCircleColor(orangeColor);
        baseLineSet.setFillColor(orangeColor);
        baseLineSet.setHighLightColor(Color.rgb(244, 177, 177));
        baseLineSet.setDrawCircleHole(false);

        LineDataSet set = new LineDataSet(new ArrayList<>(), labelName);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setMode(LineDataSet.Mode.LINEAR);
        set.setLineWidth(2f);
        set.setCircleRadius(2f);
        set.setFillAlpha(65);
        final int redColor = getResources().getColor(R.color.red_normal);
        set.setColor(redColor);
        set.setCircleColor(redColor);
        set.setFillColor(redColor);
        set.setHighLightColor(Color.rgb(244, 177, 177));
        set.setDrawCircleHole(false);

        LineData lineData = new LineData(baseLineSet, set);
        lineData.setValueTextColor(Color.BLACK);
        lineData.setValueTextSize(12f);
        lineChart.setData(lineData);
    }

    private void setLineChartParameter(LineChart lineChart) {
        lineChart.getDescription().setEnabled(false);
        lineChart.setScaleEnabled(true);
        lineChart.setDrawGridBackground(false);
        lineChart.setHighlightPerTapEnabled(true);
        lineChart.setPinchZoom(true);
        lineChart.setBackgroundColor(Color.TRANSPARENT);

        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);
        legend.setTextColor(Color.BLACK);
        legend.setMaxSizePercent(0.9f);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setAxisLineColor(getResources().getColor(R.color.colorAccent));
        xAxis.setAxisLineWidth(2f);
        xAxis.setTextSize(12f);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(220f);
        xAxis.setLabelCount(10);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value != 0f) {
                    return String.valueOf((int) value);
                } else {
                    return "";
                }
            }
        });

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setAxisLineColor(getResources().getColor(R.color.colorAccent));
        leftAxis.setTextSize(12f);
        leftAxis.setAxisLineWidth(2f);
        leftAxis.setAxisMaximum(600f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(false);
        leftAxis.setGranularityEnabled(false);

        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setDrawZeroLine(false);
        rightAxis.setGranularityEnabled(false);
        //不画刻度数字
        rightAxis.setDrawLabels(false);
        //不画竖线
        rightAxis.setDrawAxisLine(false);
    }
}
